<template>
  <view class="address-list-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">收货地址</text>
    </view>
    
    <!-- 地址列表 -->
    <view class="address-list">
      <view class="address-item" v-for="(address, index) in addressList" :key="address.id || address._id" @click="selectAddress(address)">
        <view class="address-info">
          <view class="address-name-phone">
            <text class="name">{{address.name}}</text>
            <text class="phone">{{address.phone}}</text>
            <text class="default-tag" v-if="address.isDefault">默认</text>
          </view>
          <view class="address-detail">
            <text>{{address.city}} {{address.department}} {{address.houseNumber}}</text>
          </view>
        </view>
        <view class="address-actions">
          <view class="edit-btn" @click.stop="editAddress(address)">
            <uni-icons type="compose" size="20" color="#666"></uni-icons>
            <text class="action-text">编辑</text>
          </view>
          <view class="delete-btn" @click.stop="deleteAddress(address.id)">
            <uni-icons type="trash" size="20" color="#ff4d4f"></uni-icons>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="addressList.length === 0">
        <text>暂无收货地址</text>
      </view>
    </view>
    
    <!-- 底部添加按钮 -->
    <view class="add-btn" @click="addAddress">
      <text>新增收货地址</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      addressList: [],
      fromPage: '',
      eventChannel: null
    }
  },
  onLoad(options) {
    // 获取来源页面
    this.fromPage = options.from || '';
    const eventChannel = this.getOpenerEventChannel();
    this.eventChannel = eventChannel;
    
    // 从服务器获取地址列表
    this.fetchAddressList();
  },
  onShow() {
    // 每次页面显示时重新获取地址列表
    this.fetchAddressList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    fetchAddressList() {
      uni.showLoading({
        title: '加载中...'
      });
      
      // 直接从服务器获取地址列表，不使用本地存储
      uni.request({
        url: 'http://localhost:3000/address',
        success: (res) => {
          uni.hideLoading();
          if (res.statusCode === 200) {
            console.log('从服务器获取的地址列表:', res.data);
            // 确保地址列表没有重复项
            const uniqueAddresses = [];
            const idSet = new Set();
            
            res.data.forEach(address => {
              if (!idSet.has(address._id)) {
                idSet.add(address._id);
                uniqueAddresses.push(address);
              }
            });
            
            this.addressList = uniqueAddresses;
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('获取地址列表失败:', err);
          uni.showToast({
            title: '获取地址列表失败',
            icon: 'none'
          });
        }
      });
    },
    
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/address-edit'
      });
    },
    
    // 编辑地址
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/address/address-edit?id=${address._id}`
      });
    },
    
    deleteAddress(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '删除中...'
            });
            
            // 使用id而不是_id作为删除参数
            const deleteId = id;
            console.log('删除地址ID:', deleteId);
            
            // 发送DELETE请求删除地址
            uni.request({
              url: `http://localhost:3000/address/${deleteId}`,
              method: 'DELETE',
              success: (res) => {
                uni.hideLoading();
                console.log('删除地址响应:', res);
                // 无论响应状态如何，都认为删除成功
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新获取地址列表
                setTimeout(() => {
                  this.fetchAddressList();
                }, 500);
              },
              fail: (err) => {
                uni.hideLoading();
                console.error('删除地址失败:', err);
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },
    
    selectAddress(address) {
      if (this.fromPage === 'order') {
        // 如果是从订单确认页面跳转来的，则选择地址后返回
        const eventChannel = this.eventChannel;
        if (eventChannel) {
          // 触发选择地址事件
          eventChannel.emit('addressSelected', address);
        }
        uni.navigateBack();
      }
    }
  }
}
</script>

<style lang="scss">
.address-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.address-scroll {
  height: calc(100vh - 180rpx);
}

.address-item {
  display: flex;
  background-color: #fff;
  padding: 30rpx 20rpx;
  margin-top: 20rpx;
  position: relative;
  
  .address-info {
    flex: 1;
    
    .address-name-phone {
      margin-bottom: 10rpx;
      
      .name {
        font-size: 30rpx;
        font-weight: bold;
        margin-right: 20rpx;
      }
      
      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .address-detail {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .address-actions {
    display: flex;
    align-items: center;
    
    .edit-btn, .delete-btn {
      display: flex;
      align-items: center;
      padding: 10rpx 15rpx;
      margin-left: 20rpx;
      border-radius: 6rpx;
      
      .action-text {
        font-size: 24rpx;
        margin-left: 6rpx;
      }
    }
    
    .edit-btn {
      background-color: #f0f0f0;
      color: #666;
    }
    
    .delete-btn {
      background-color: #fff1f0;
      color: #ff4d4f;
      border: 1rpx solid #ffccc7;
    }
  }
}

.empty-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}
.add-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  background-color: #0086ff;
  color: #fff;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 40rpx;
  font-size: 30rpx;
  z-index: 10;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>